package com.example.rabbitboot.receiver;

import com.example.rabbitboot.config.RabbitDirectConfig;
import com.example.rabbitboot.config.RabbitTopicConfig;
import com.example.rabbitboot.connect.RabbitConnect;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lzh
 * @date 2019/9/18 - 16:07
 */
@Configuration
public class DefaultRabbitReceiver {

    @Autowired
    private RabbitConnect rabbitConnect;

    @Autowired
    private RabbitTopicConfig rabbitExchangeConfig;



    @Bean
    public SimpleMessageListenerContainer messageContainer() {
        //用连接工厂 初始化 rabbitmq连接
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(rabbitConnect.connectionFactory());

        //设置要监听的队列
        container.setQueues(rabbitExchangeConfig.getTopicQueue1());


        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);

        //设置确认模式手工确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                System.out.println("receive msg : " + new String(body));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
            }
        });
        return container;
    }
}
